package com.example.node.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;
import com.example.node.adapter.ViewPagerAdapter;
import com.example.node.listener.OnClick;

import java.util.ArrayList;
import java.util.List;

public class AutoViewPager extends ViewPager {

    private OnClick onClick;

    public void setOnClick(OnClick onClick) {
        this.onClick = onClick;
    }

    private static final int AUTO_WANT=0X11;
    //数据源
    private List<View> mList=new ArrayList<>();
    //轮播开关
    private boolean isStartAuto=false;
    //轮播时长
    private int autoTime=3000;

    @SuppressLint("HandlerLeak")
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case AUTO_WANT:
                    if(isStartAuto){
                        int index=getCurrentItem();
                        //如果当前item超过了最大页数
                        if(index>=mList.size()-1){
                            setCurrentItem(0);
                        }else {
                            setCurrentItem(index+1);
                        }
                        handler.sendEmptyMessageDelayed(AUTO_WANT,autoTime);
                    }
                    break;
            }
        }
    };

    public AutoViewPager(@NonNull Context context) {
        super(context);
    }

    public AutoViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    //设置轮播间隔时间
    public void setAutoTime(int autoTime) {
        this.autoTime = autoTime;
    }

    //获取轮播间隔时间
    public int getAutoTime() {
        return autoTime;
    }

    //启动轮播
    public void setStartAuto(boolean startAuto) {
        isStartAuto = startAuto;
        if(isStartAuto){
            handler.sendEmptyMessage(AUTO_WANT);
        }else {
            handler.removeMessages(AUTO_WANT);
        }
    }

    public boolean getStartAuto(){
        return isStartAuto;
    }

    //获取当前轮播状态
    public boolean isStartAuto() {
        return isStartAuto;
    }

    //设置View
    public void setView(View view){
        mList.add(view);
        setAdapter(new ViewPagerAdapter(mList));
        view.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }
}
